package ten;

public class HappyCinema {
    public static void main(String[] args) {
        Cinema c = new Cinema(2, "快乐影院");
        new Thread(new Customer(c, 1), "老裴").start();
        new Thread(new Customer(c, 2), "老高").start();
    }
}

class Cinema {
    int available;
    String name;

    public Cinema(int available, String name) {
        this.available = available;
        this.name = name;
    }

    public boolean buyTickets(int seats) {
        System.out.println("可用位置为: " + available);
        if (seats > available) {
            return false;
        }
        available -= seats;
        return true;
    }
}

class Customer implements Runnable {
    Cinema cinema;
    int seats;

    public Customer(Cinema cinema, int seats) {
        this.cinema = cinema;
        this.seats = seats;
    }

    @Override
    public void run() {
        synchronized (cinema) {
            boolean flag = cinema.buyTickets(seats);
            if (flag) {
                System.out.println("出票成功,"
                        + Thread.currentThread().getName()
                        + "-<位置为: "
                        + seats);
            } else {
                System.out.println("出票失败,"
                        + Thread.currentThread().getName()
                        + "-<位置不够");
            }
        }
    }
}
